define(function(require, exports, module) {
	module.exports = function() {
		var app = angular.module('ProjectManage.controllers');
		app.controller('todostaffCtrl', ['$scope', '$http', '$location', '$rootScope',
			function($scope, $http, $location, $rootScope) {
				var todoprojects = {};

				function initial() {
					$rootScope.todostaffs = JSON.parse(localStorage.getItem("todostaffs"));
					angular.forEach($rootScope.todostaffs, function(item, key) {
						item.used = false;
					});
					todoprojects = JSON.parse(localStorage.getItem("todoprojects"));
				};
				initial();


				//初始化所有变量$scope
				$scope.options = function() {
					var str = "市内白班,市内白+黑,监护长夜班,外地白班,外地白+黑,请假,安排休息";
					return str.split(',');
				}();

				$scope.hours = function() {
					var h = 0;
					angular.forEach(todoprojects, function(prj) {
						h = h + prj.Hours;
					});
					return h;
				}();

				//checked的变化
				$scope.change1 = function(index) {
					if (index != null) {
						$rootScope.todostaffs[index].checked = !$rootScope.todostaffs[index].checked;
					}
					var count = 0;
					angular.forEach($rootScope.todostaffs, function(staff) {
						staff.used = false;
						if (staff.checked === true) {
							count++;
						}
					});
					var hour = Math.round(100 * $scope.hours / count) / 100;
					angular.forEach($rootScope.todostaffs, function(staff) {
						if (staff.checked === true) {
							staff.Hours = hour;
						} else {
							staff.Hours = 0;
						}
					});
				}
				$scope.change1();

				$scope.change2 = function(index) {
					var usedHours = 0;
					var unUsed = 0;
					$rootScope.todostaffs[index].used = true;
					//求和  计数
					angular.forEach($rootScope.todostaffs, function(staff, i) {
						if (staff.checked === false) return;
						if (staff.used === false) {
							unUsed++;
						} else if (staff.used === true) {
							usedHours += $rootScope.todostaffs[i].Hours;
						}
					});
					if (unUsed === 0) {
						$rootScope.todostaffs[index].Hours = $scope.hours - (usedHours - $rootScope.todostaffs[index].Hours);
						return;
					}
					var hour = Math.round(100 * ($scope.hours - usedHours) / unUsed) / 100;
					angular.forEach($rootScope.todostaffs, function(staff, i) {
						if ($rootScope.todostaffs[i].checked === true && staff.used === false) {
							$rootScope.todostaffs[i].Hours = hour;
						}
					});
				};


				$scope.nextStep = function() {
					var dataPost = {
						'name': $rootScope.user.name,
						'todoprojects': todoprojects,
						'todostaffs': $rootScope.todostaffs,
						'date': $rootScope.date
					};
					$http({
						url: '/workhours',
						method: 'post',
						data: dataPost
					}).success(function(data) {
						//clear local data


						$location.path('/success');
					});
				}
			}

		]);
	}
});